﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWeb.Business;
using MyWeb.Common;
using MyWeb.Data;

namespace MyWeb.TrangChinh.UC
{
    public partial class ucShoppingCart : UserControl
    {
        private readonly OrderDetailService _orderDetailService = new OrderDetailService();
        private readonly OrderService _orderService = new OrderService();
        private decimal _total;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var cart = Session["Cart"] as DataTable;
                gvData.DataSource = cart;
                gvData.DataBind();
            }
        }

        public string Format_Price(string values)
        {
            values = values.Replace(",", "");
            values = values.Replace(".", "");
            string s = "";
            while (values.Length > 3)
            {
                s = "." + values.Substring(values.Length - 3) + s;
                values = values.Substring(0, values.Length - 3);
            }
            s = values + s;
            return s;
        }

        protected void btnDathang_Click(object sender, EventArgs e)
        {
            if (Session["user_id"] == null)
            {
                Session["historyweb"] = Request.QueryString["idProduct"];
                Response.Redirect("~/TrangChinh/Login.aspx");
            }
            else
            {
                var dtCart = Session["Cart"] as DataTable;
                if (dtCart.Rows.Count != 0)
                {
                    var order = new OrderInfo
                                    {
                                        User_Id = Int32.Parse(Session["user_id"].ToString()),
                                        TotalMoney = float.Parse(lblTongtien.Text),
                                        Date = DateTime.Now,
                                        Status = 0
                                    };
                    _orderService.Order_Insert(order);
                    int orderId = _orderService.Order_GetId();
                    var orderDetail = new OrderDetailInfo {Order_Id = orderId};
                    for (int i = 0; i < dtCart.Rows.Count; i++)
                    {
                        orderDetail.Product_Id = Int32.Parse(dtCart.Rows[i]["Id"].ToString());
                        orderDetail.Quantity = Int32.Parse(dtCart.Rows[i]["Quantity"].ToString());
                        _orderDetailService.OrderDetail_Insert(orderDetail);
                    }
                }
                else
                {
                    WebMsgBox.Show("Chưa có mặt hàng nào trong giỏ hàng");
                }
            }
        }

        protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string ID = e.CommandArgument.ToString();
            if (e.CommandName == "Update")
            {
                for (int i = 0; i < gvData.Rows.Count; i++)
                {
                    var txtQuantity = (TextBox) gvData.Rows[i].FindControl("txtquantity");
                    var lblprice = (Label) gvData.Rows[i].FindControl("lblprice");
                    var totalmoney = (Label) gvData.Rows[i].FindControl("lbltotalmoney");
                    lblprice.Text = lblprice.Text.Substring(0, lblprice.Text.LastIndexOf("VNĐ"));
                    if (txtQuantity.Text.Trim().Equals("0"))
                    {
                        txtQuantity.Text = "1";
                        totalmoney.Text = (Int32.Parse(lblprice.Text.Replace(".", ""))*
                                           Int32.Parse(txtQuantity.Text.Trim())) +
                                          " VNĐ";
                    }
                    else
                    {
                        totalmoney.Text = (Int32.Parse(lblprice.Text.Replace(".", ""))*
                                           Int32.Parse(txtQuantity.Text.Trim())) +
                                          " VNĐ";
                    }
                    lblprice.Text = lblprice.Text + " VNĐ";
                    CartUpdate((DataTable) Session["Cart"], ID, txtQuantity.Text);
                }
                Response.Redirect(Request.Url.LocalPath);
            }
            else
            {
                var dt = new DataTable();
                dt = (DataTable) Session["Cart"];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["id"].ToString().Equals(ID))
                    {
                        dt.Rows.RemoveAt(i);
                    }
                }
                Response.Redirect(Request.Url.LocalPath);
            }
        }

        private void CartUpdate(DataTable cart, string prid, string inumber)
        {
            if (cart.Rows.Count > 0)
            {
                for (int i = 0; i < cart.Rows.Count; i++)
                {
                    if (cart.Rows[i]["id"].ToString().Equals(prid))
                    {
                        cart.Rows[i]["quantity"] = inumber;
                        cart.Rows[i]["totalmoney"] = Int32.Parse(inumber)*
                                                     float.Parse(cart.Rows[i]["pricenew"].ToString());
                        break;
                    }
                }
            }
        }

        protected void btnMuatiep_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx");
        }

        protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var lbltotalmoney = (Label) e.Row.FindControl("lbltotalmoney");
                decimal totalmoney = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "pricenew"))*
                                     Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "quantity"));
                lbltotalmoney.Text = totalmoney.ToString();
                _total += totalmoney;
            }
            lblTongtien.Text = Format_Price(_total.ToString());
        }
    }
}